/**
 * @description  : 工具类
 * @descriptionDetail : 工具类
 * @copyright    : 浙江烟草
 * @author       : mc
 * @create       : 2022-09-04 16:49:00
 */
function formatTime(time) {
  if (typeof time !== 'number' || time < 0) {
    return time;
  }

  let hour = parseInt(time / 3600);
  time = time % 3600;
  let minute = parseInt(time / 60);
  time = time % 60;
  let second = time;

  return ([hour, minute, second,]).map(function (n) {
    n = n.toString();
    return n[1] ? n : '0' + n;
  }).join(':');
}

function formatLocation(longitude, latitude) {
  if (typeof longitude === 'string' && typeof latitude === 'string') {
    longitude = parseFloat(longitude);
    latitude = parseFloat(latitude);
  }

  longitude = longitude.toFixed(2);
  latitude = latitude.toFixed(2);

  return {
    longitude: longitude.toString().split('.'),
    latitude: latitude.toString().split('.'),
  };
}
let dateUtils = {
  UNITS: {
    '年': 31557600000,
    '月': 2629800000,
    '天': 86400000,
    '小时': 3600000,
    '分钟': 60000,
    '秒': 1000,
  },
  humanize: function (milliseconds) {
    let humanize = '';
    for (let key in this.UNITS) {
      if (milliseconds >= this.UNITS[key]) {
        humanize = Math.floor(milliseconds / this.UNITS[key]) + key + '前';
        break;
      }
    }
    return humanize || '刚刚';
  },
  format: function (dateStr) {
    let date = this.parse(dateStr);
    let diff = Date.now() - date.getTime();
    if (diff < this.UNITS['天']) {
      return this.humanize(diff);
    }
    let dFormat = function (number) {
      return (number < 10 ? ('0' + number) : number);
    };
    return date.getFullYear() + '/' + dFormat(date.getMonth() + 1) + '/' + dFormat(date.getDate()) + '-' +
      dFormat(date.getHours()) + ':' + dFormat(date.getMinutes());
  },
  dateFormat: function dateFormat(fmt, date) {
    if (typeof date === 'number') {
      date = new Date(date);
    }
    let ret;
    const opt = {
      "yyyy": date.getFullYear().toString(),        // 年
      "MM": (date.getMonth() + 1).toString(),     // 月
      "dd": date.getDate().toString(),            // 日
      "HH": date.getHours().toString(),           // 时
      "mm": date.getMinutes().toString(),         // 分
      "ss": date.getSeconds().toString(),          // 秒
    };
    for (let k in opt) {
      ret = new RegExp("(" + k + ")").exec(fmt);
      if (ret) {
        fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")));
      }
    }
    return fmt;
  },
  parse: function (str) { // 将"yyyy-mm-dd HH:MM:ss"格式的字符串，转化为一个Date对象
    let a = str.split(/[^0-9]/);
    return new Date(a[0], a[1] - 1, a[2], a[3], a[4], a[5]);
  },
  firstDate: function (d) {
    return new Date(d.setDate(1));
  },
  // 获取当年第一天
  firstYearDate:function (d) {
    d.setDate(1);
    d.setMonth(0);
    return new Date(d);
  },
  lastDate: function (d) {
    let fullYear = d.getFullYear();
    let month = d.getMonth() + 1;
    // 获取本月最后一天
    let endOfMonth = new Date(fullYear, month, 0).getDate();
    return new Date(d.setDate(endOfMonth));
  },
  // 本周的开始时间
  getStartDayOfWeek() {
    let now = new Date();
    let day = now.getDay() || 7;
    let nowDay = now.getDate(); // 当前日
    let nowMonth = now.getMonth(); // 当前月
    return this.dateFormat("yyyy-MM-dd", new Date(now.getFullYear(), nowMonth, nowDay + 1 - day));
  },
  // 本周的结束时间
  getEndDayOfWeek() {
    let now = new Date();
    let day = now.getDay() || 7;
    let nowDay = now.getDate(); // 当前日
    let nowMonth = now.getMonth(); // 当前月
    return this.dateFormat("yyyy-MM-dd", new Date(now.getFullYear(), nowMonth, nowDay + 7 - day));
  },
};

function isIOS() {
  return window.navigator.userAgent.match(/(iPad|iPhone|iPod)/i) ? true : false;
}

function isAndroid() {
  return window.navigator.userAgent.match(/(Android)/i) ? true : false;
}

/**
 * 判断当前是否钉钉环境
 * @returns true 是 false 否
 */
function isDD()  {
  return /DingTalk/.test(window.navigator.userAgent);
}

/**
 * 判断企业微信环境
 * @returns true 是 false 否
 */
function isWorkWechat() {
  let ua = window.navigator.userAgent;
  return /MicroMessenger/.test(ua);
}

/**
 * 判断emp环境
 * @returns true 是 false 否
 */
function isEmpApp() {
  let ua = window.navigator.userAgent;
  return /EMP/.test(ua);
}

function getNavBarHeight() {
  let e = uni.getSystemInfoSync();
  let statusBar = 0;
  let customBar = 0;
  // #ifdef MP
  statusBar = e.statusBarHeight;
  customBar = e.statusBarHeight + 45;
  if (e.platform === 'android') {
    this.$store.commit('SET_SYSTEM_IOSANDROID', false);
    customBar = e.statusBarHeight + 50;
  }
  // #endif

  // #ifdef MP-WEIXIN
  statusBar = e.statusBarHeight;
  // @ts-ignore
  const custom = wx.getMenuButtonBoundingClientRect();
  customBar = custom.bottom + custom.top - e.statusBarHeight;
  // #endif

  // #ifdef MP-ALIPAY
  statusBar = e.statusBarHeight;
  customBar = e.statusBarHeight + e.titleBarHeight;
  // #endif

  // #ifdef APP-PLUS
  console.log('app-plus', e);
  statusBar = e.statusBarHeight;
  customBar = e.statusBarHeight + 45;
  // #endif

  // #ifdef H5
  statusBar = 0;
  customBar = e.statusBarHeight + 45;
  // #endif
  return [customBar, statusBar,];
  // // 这里你可以自己决定存放方式，建议放在store中，因为store是实时变化的
  //   this.$store.commit('SET_STATUS_BAR', statusBar)
  //   this.$store.commit('SET_CUSTOM_BAR', customBar)
  //   this.$store.commit('SET_SYSTEM_INFO', e)
}
/**
 * promise 输出转码为base64的文件字符串
 */
function chooseImg() {
  return new Promise(function (resolve, reject) {
    uni.chooseImage({
      count: 1, // 默认9
      sizeType: ['compressed',],
      sourceType: ['album',], // 从相册选择
      success: (res) => {
        uni.showLoading({
          title: '加载中...',
        });
        base64Img(res.tempFilePaths[0]).then(
          (data) => {
            uni.hideLoading();
            console.log('====' + data);
            resolve(data);
          },
          (err) => {
            uni.hideLoading();
            reject(err);
          }
        );
      },
    });
  });
}
/**
 * 将base64编码的图片旋转指定度数(90的整数倍数)
 * @param {*} src     base64编码图片
 * @param {*} edg     旋转度数
 * @param {*} callback  回调函数
 */
function rotateBase64Img(src, edg, callback) {
  let canvas = document.createElement("canvas");
  let ctx = canvas.getContext("2d");

  let imgW;// 图片宽度
  let imgH;// 图片高度
  let size;// canvas初始大小

  if (edg % 90 != 0) {
    console.error("旋转角度必须是90的倍数!");
    throw '旋转角度必须是90的倍数!';
  }
  (edg < 0) && (edg = (edg % 360) + 360);
  const quadrant = (edg / 90) % 4; // 旋转象限
  const cutCoor = {sx: 0, sy: 0, ex: 0, ey: 0,}; // 裁剪坐标
  let image = new Image();
  image.crossOrigin = "anonymous";
  image.src = src;

  image.onload = function () {
    imgW = image.width;
    imgH = image.height;
    size = imgW > imgH ? imgW : imgH;

    canvas.width = size * 2;
    canvas.height = size * 2;
    switch (quadrant) {
    case 0:
      cutCoor.sx = size;
      cutCoor.sy = size;
      cutCoor.ex = size + imgW;
      cutCoor.ey = size + imgH;
      break;
    case 1:
      cutCoor.sx = size - imgH;
      cutCoor.sy = size;
      cutCoor.ex = size;
      cutCoor.ey = size + imgW;
      break;
    case 2:
      cutCoor.sx = size - imgW;
      cutCoor.sy = size - imgH;
      cutCoor.ex = size;
      cutCoor.ey = size;
      break;
    case 3:
      cutCoor.sx = size;
      cutCoor.sy = size - imgW;
      cutCoor.ex = size + imgH;
      cutCoor.ey = size + imgW;
      break;
    }

    ctx.translate(size, size);
    ctx.rotate(edg * Math.PI / 180);
    ctx.drawImage(image, 0, 0);

    let imgData = ctx.getImageData(cutCoor.sx, cutCoor.sy, cutCoor.ex, cutCoor.ey);
    if (quadrant % 2 == 0) {
      canvas.width = imgW;
      canvas.height = imgH;
    } else {
      canvas.width = imgH;
      canvas.height = imgW;
    }
    ctx.putImageData(imgData, 0, 0);
    callback(canvas.toDataURL());
  };
}
/**
 * 获取
 * @param {Vue} self 当前Vue对象
 * @param {Array} arr 子组件的ref  name
 * @return {Promise} resolve  reject
 */
function getImgUploadData(self, arr) {
  return new Promise(function(resolve, reject) {
    if (arr && arr.length > 0) {
      let result = new Array();
      for (let i = 0; i < arr.length; i++) {
        let vm = getRefsVueObj(self, arr[i]);
        let tmp = vm.getUploadData();
        if (tmp == null) {
          if (vm.isMust) {
            reject();
            return;
          }
          continue;
        }
        result.push(tmp);
      }
      resolve(result);
      return;
    }
    reject();
  });
}
function getRefsVueObj(self, refName) {
  let ar = self.$refs[refName];
  if (ar instanceof Array) {
    return ar[0];
  } else {
    return ar;
  }
}
/**
 * @param {Object} path
 */
function base64Img(path) {
  return new Promise(function(resolve, reject) {
    // 使用Promise进行异步处理
    let image = new Image();
    // 解决图片跨域问题
    image.crossOrigin = '';
    // 获取传入的图片路径
    image.src = path;
    // 图片加载完后的回调函数,调用转码函数
    image.onload = function() {
      resolve(getBase64Image(image)); // 回调函数返回base64值
    };
  });
}

function dataURLtoFile(dataurl, filename) { // 将base64转换为文件
  let arr = dataurl.split(','); let mime = arr[0].match(/:(.*?);/)[1];
  let bstr = atob(arr[1]); let n = bstr.length; let u8arr = new Uint8Array(n);
  while(n--){
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr,], filename, {type:mime,});
}

function getBase64Image(img) {
  // 转码格式方法
  let canvas = document.createElement('canvas'); // 创建一个canvas
  canvas.width = img.width; // 设置对应的宽高
  canvas.height = img.height;
  let ctx = canvas.getContext('2d'); // 二维绘图环境
  ctx.drawImage(img, 0, 0, img.width, img.height); // 将图片画在画布上
  let ext = img.src.substring(img.src.lastIndexOf('.') + 1).toLowerCase(); // 获取到图片的格式
  let dataURL = canvas.toDataURL('image/' + ext); // 得到base64 编码的 dataURL
  return dataURL;
}
/**
 * 获取图片的原始尺寸
 * @param {Object} path
 */
function getImgNaturalSize(path) {
  return new Promise(function(resolve, reject) {
    // 使用Promise进行异步处理
    let image = new Image();
    // 解决图片跨域问题
    image.crossOrigin = '';
    // 获取传入的图片路径
    image.src = path;
    // 图片加载完后的回调函数,调用转码函数
    image.onload = function() {
      resolve([image.width, image.height,]); // 回调函数返回base64值
    };
  });
}

function S4() {
  return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
/**
 * 生成Uuid
 */
function uuid() {
  let uuid = S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
  return uuid.replace(/-/g, '');
}
/**
 * 文书拆分人员数据为对象 例如承办人
 * @param employee
 */
function splitEmployeeList(employee){
  let employeeLst = [];
  if(employee && employee != ''){
    let items = employee.split(",");
    console.log(items);
    for(let i = 0 ; i < items.length;i++){
      let employeeItem = {};
      let item = items[i].split("(");
      console.log(item[0]);
      employeeItem.employeeName = item[0];
      if(item[1] && item[1] != ''){
        employeeItem.leCertNo = item[1].replace(")","");
      }
      employeeLst.push(employeeItem);
    }
    return employeeLst;
  }
}
/**
		 * 经纬度校验
		 * 经度：要求经度整数部分为0-180小数部分为0到6位！
		 * 纬度：要求纬度整数部分为0-90小数部分为0到6位！
		 */
function valGisXY(type,value){
  let reg;
  let numXY;
  let gis = value;
  // 经度
  if(type == '1'){
    reg = /^(((\d|[1-9]\d|1[0-7]\d|0)\.\d{0,6})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,6}|180)$/;
    if(!reg.test(gis)){
      numXY = (180.0).toFixed(6);
    }else{
      numXY = Number(gis).toFixed(6)
    }

  }else{
    // 纬度
    let numY;
    reg = /^([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/;
    if(!reg.test(gis)){
      numXY = (90.0).toFixed(6);
    }else{
      numXY = Number(gis).toFixed(6)
    }
  }
  return numXY;
}
// 回显省市县 字符串转换成 picker 组件需要的数组
function getRegionArrayByStr(str, list) {
  let regionArray = (!!str && str.split(',')) || [];
  if(regionArray.length < 3) return [];
  let arp = [];
  let ar = list.filter(itm => {
    return itm.value == regionArray[0];
  });
  if(ar.length == 1){
    arp.push(ar[0].extra.index);
    let app = ar[0].children.filter(ip => {
      return ip.value == regionArray[1];
    });
    if(app.length == 1){
      arp.push(app[0].extra.index);
      let xpp = app[0].children.filter(ipx => {
        return ipx.value == regionArray[2];
      });
      if(xpp.length == 1){
        arp.push(xpp[0].extra.index);
      }
    }
  }
  return arp;
}
// 传入 省市县编码 数组, 省市县原始数组(多维)
function getRegionNameByCodes(arr, list) {
  if(arr.length != 3) return "";
  let nameArr = [];
  try{
    nameArr.push(list[arr[0]].name);
    nameArr.push(list[arr[0]].chlidren[arr[1]].name);
    nameArr.push(list[arr[0]].chlidren[arr[1]].children[arr[2]].name);
  }catch(e){
    console.log(e);
  }
  return nameArr.join('-');
}
// 解析人员
function parseEmployee(rs,idName,namef) {
  let namVal = namef ? rs[namef] : rs.undertaker;
  let idVal = idName ? rs[idName] : rs.undertakerUuids;
  if (!namVal || !idVal) {
    return [];
  }
  let takers = namVal.split(',');
  let uuids = idVal.split(',');
  let takerArr = [];
  for (let i = 0; i < takers.length; i++) {
    let a = takers[i];
    let vl = a.replace(')', '');
    let vls = vl.split('(');
    let no = vls[1] || '';
    no = no === 'null' || no === 'undefined' ? '' : no;
    takerArr.push({personName: vls[0], leCertNo: no, personUuid: uuids[i],});
  }
  return takerArr;
}

// 大小写金额转换
function getUpper(n){
  let fraction = ['角', '分',];
  let digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖',];
  let unit = [['元', '万', '亿',], ['', '拾', '佰', '仟',],];
  let head = n < 0 ? '欠' : '';
  n = Math.abs(n);
  let s = '';
  let str = n + "";
  for (let i = 0; i < fraction.length; i++){
    if(str.indexOf(".") != -1){
      if(str.substring(str.indexOf(".") + 1,str.length).length > i)
        s += (digit[str.substring(str.indexOf(".") + 1 + i,str.indexOf(".") + 2 + i)] + fraction[i]).replace(/零./, '');
    }
  }
  s = s || '整';
  n = Math.floor(n);

  for (let i = 0; i < unit[0].length && n > 0; i++){
    let p = '';
    for (let j = 0; j < unit[1].length && n > 0; j++){
      p = digit[n % 10] + unit[1][j] + p;
      n = Math.floor(n / 10);
    }
    s = p.replace(/(零.)*零$/, '').replace(/^$/, '零')  + unit[0][i] + s;
  }
  return head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
}

// 队列对象
function Queue() {
  this.data = [];
  this.enqueue = enqueue;// 队尾添加一个元素
  this.dequeue = dequeue;// 队首删除一个元素
  this.front = front;    // 读取队首元素
  this.back = back;      // 读取队尾元素
  this.toStringData = toStringData;// 显示队内元素
  this.isEmpty = isEmpty;// 判断队列是否为空

  // 在队尾添加一个元素即为入队
  function enqueue(element) {
    this.data.push(element);
  }
  // 在队首删除一个元素，并返回被删除的值
  function dequeue() {
    return this.data.shift();
  }
  // 返回数组第一项即返回队首元素
  function front() {
    return this.data[0];
  }
  // 返回数组最后一项即返回队尾元素
  function back() {
    return this.data[this.data.length - 1];
  }
  // 数组长度为0即队列为空
  function isEmpty() {
    return this.data.length === 0;
  }
  // 打印队列
  function toStringData() {
    return this.data;
  }
}

function getByteLength(str = '') {
  let len = 0;
  for (let i = 0; i < str.length; i++) {
    if (str.charCodeAt(i) > 127 || str.charCodeAt(i) == 94) {
      len += 2;
    } else {
      len++;
    }
  }
  return len;
}
// 通过身份证号码 获取 出生年月日 年龄 性别
function getGenderByIdNumber(idCard) {
  console.log(idCard);
  let idInfo = {
    birthdayArr: [],
    age: '',
    sex: '',
    birthday: '',
  };
  if (!idCard) {
    return idInfo;
  }
  let currData = new Date();
  let currDataArr = [currData.getFullYear(), currData.getMonth() + 1, currData.getDate(),];
  let sexCode = '';

  if (15 === idCard.length) {
    idInfo.birthdayArr = ['19' + idCard.substring(6, 8), idCard.substring(8, 10), idCard.substring(10, 12),];
    sexCode = parseInt(idCard.substr(14, 1)) % 2;
  }
  if (18 === idCard.length) {
    idInfo.birthdayArr = [idCard.substring(6, 10), idCard.substring(10, 12), idCard.substring(12, 14),];
    sexCode = parseInt(idCard.substr(16, 1)) % 2;
  }
  let age = currDataArr[0] - idInfo.birthdayArr[0];
  if (currDataArr[1] < idInfo.birthdayArr[1] || (currDataArr[1] == idInfo.birthdayArr[1] && currDataArr[2] < idInfo.birthdayArr[2])) {
    age--;
  }
  idInfo.age = age || '';
  idInfo.sex = sexCode;
  idInfo.birthday = idInfo.birthdayArr.join('-');

  console.log(idInfo);
  return idInfo;
}

/**
 * 加法函数，用来得到精确的加法结果
 * 说明：javascript的加法结果会有误差，在两个浮点数相加的时候会比较明显。这个函数返回较为精确的加法结果。
 * 调用：accAdd(arg1,arg2)
 * 返回值：arg1加上arg2的精确结果
 **/
function accAdd(arg1, arg2) {
  var r1, r2, m, c;
  try {
    r1 = arg1.toString().split('.')[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split('.')[1].length;
  } catch (e) {
    r2 = 0;
  }
  c = Math.abs(r1 - r2);
  m = Math.pow(10, Math.max(r1, r2));
  if (c > 0) {
    var cm = Math.pow(10, c);
    if (r1 > r2) {
      arg1 = Number(arg1.toString().replace('.', ''));
      arg2 = Number(arg2.toString().replace('.', '')) * cm;
    } else {
      arg1 = Number(arg1.toString().replace('.', '')) * cm;
      arg2 = Number(arg2.toString().replace('.', ''));
    }
  } else {
    arg1 = Number(arg1.toString().replace('.', ''));
    arg2 = Number(arg2.toString().replace('.', ''));
  }
  return (arg1 + arg2) / m;
}
/**
 * 减法函数，用来得到精确的减法结果
 * 说明：javascript的减法结果会有误差，在两个浮点数相减的时候会比较明显。这个函数返回较为精确的减法结果。
 * 调用：accSub(arg1,arg2)
 * 返回值：arg1加上arg2的精确结果
 **/
function accSub(arg1, arg2) {
  var r1, r2, m, n;
  try {
    r1 = arg1.toString().split('.')[1].length;
  } catch (e) {
    r1 = 0;
  }
  try {
    r2 = arg2.toString().split('.')[1].length;
  } catch (e) {
    r2 = 0;
  }
  m = Math.pow(10, Math.max(r1, r2)); //last modify by deeka //动态控制精度长度
  n = r1 >= r2 ? r1 : r2;
  return ((arg1 * m - arg2 * m) / m).toFixed(n);
}
/**
 *  乘法函数，用来得到精确的乘法结果
 *  说明：javascript的乘法结果会有误差，在两个浮点数相乘的时候会比较明显。这个函数返回较为精确的乘法结果。
 *  调用：accMul(arg1,arg2)
 *  返回值：arg1乘以 arg2的精确结果
 **/
function accMul(arg1, arg2) {
  var m = 0,
    s1 = arg1.toString(),
    s2 = arg2.toString();
  try {
    m += s1.split('.')[1].length;
  } catch (e) { }
  try {
    m += s2.split('.')[1].length;
  } catch (e) { }
  return (Number(s1.replace('.', '')) * Number(s2.replace('.', ''))) / Math.pow(10, m);
}
/**
 *  除法函数，用来得到精确的除法结果
 *  说明：javascript的除法结果会有误差，在两个浮点数相除的时候会比较明显。这个函数返回较为精确的除法结果。
 *  调用：accDiv(arg1,arg2)
 *  返回值：arg1除以arg2的精确结果
 **/
function accDiv(arg1, arg2) {
  var t1 = 0,
    t2 = 0,
    r1,
    r2;
  try {
    t1 = arg1.toString().split('.')[1].length;
  } catch (e) {}
  try {
    t2 = arg2.toString().split('.')[1].length;
  } catch (e) {}
  with (Math) {
    r1 = Number(arg1.toString().replace('.', ''));
    r2 = Number(arg2.toString().replace('.', ''));
    return (r1 / r2) * pow(10, t2 - t1);
  }
}

module.exports = {
  formatTime: formatTime,
  formatLocation: formatLocation,
  dateUtils: dateUtils,
  isIOS: isIOS,
  isAndroid: isAndroid,
  getNavBarHeight: getNavBarHeight,
  chooseImg: chooseImg,
  getImgUploadData: getImgUploadData,
  getRefsVueObj: getRefsVueObj,
  getImgNaturalSize: getImgNaturalSize,
  rotateBase64Img: rotateBase64Img,
  uuid: uuid,
  splitEmployeeList: splitEmployeeList,
  valGisXY:valGisXY,
  getRegionArrayByStr:getRegionArrayByStr,
  getRegionNameByCodes:getRegionNameByCodes,
  parseEmployee:parseEmployee,
  getUpper:getUpper,
  dataURLtoFile:dataURLtoFile,
  Queue:Queue,
  getByteLength: getByteLength,
  getGenderByIdNumber:getGenderByIdNumber,
  isDD:isDD,
  isWorkWechat: isWorkWechat,
  isEmpApp: isEmpApp,
  accAdd: accAdd,
  accSub: accSub,
  accMul: accMul,
  accDiv: accDiv,
};
